package Longing.lock;

import Longing.demo6;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
         * @Author 枫城
         * @Date 2022/4/7
         * @Param 这个程序开启一个事务，这是事务专门进行查询，并且使用行级锁（悲观锁），锁住相关记录
         * @return 
         **/
public class text_1 {
            public static void main(String[] args) {
                Connection connection = null;
                PreparedStatement ps = null;
                ResultSet resultSet = null;
                try {
                    connection = demo6.DBUtil.getConnection();
                    // 开启事务
                    connection.setAutoCommit(false);
                    String sql = " select * from user  where combat_value >= ? for update";

                    ps = connection.prepareStatement(sql);
                    ps.setInt(1,50000);
                    // 提交事务（事务结束）
                    resultSet = ps.executeQuery();
                    while (resultSet.next()){
                        String a = resultSet.getString("user_id");  // 注意sql语句的as，根据sql语句语句来转换
                        String b = resultSet.getString("user_name");
                        String c = resultSet.getString("pwd");
                        String d = resultSet.getString("user_rename");
                        String e = resultSet.getString("combat_value");
                        System.out.println(a + " | " + b + " | " + c + " | " + d +" | "+ e );
                    }
                    connection.commit();
                } catch (SQLException e) {
                    // 回滚事务（事务结束）
                    if (connection != null){
                        try {
                            connection.rollback();
                        } catch (SQLException throwables) {
                            throwables.printStackTrace();
                        }
                    }
                    e.printStackTrace();
                }finally {
                    demo6.DBUtil.close(connection, ps, resultSet );
                }

            }
    
}
